package com.panghl.service;

import com.panghl.domain.LoginUser;
import com.panghl.domain.ResponseResult;
import com.panghl.domain.User;
import com.panghl.utils.JwtUtil;
import com.panghl.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author panghl
 * @Date 2022/2/12
 * @Description 登录实现类
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //AuthenticationManager  authenticate 进行用户认证 --->调用ProviderManager authenticate--->再去调用UserDetailsServiceImpl
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过给出对应的提示
        if (Objects.isNull(authenticationToken)) {
            throw new RuntimeException("登录失败");
        }

        //如果认证通过了，使用userid生成一个jwt  jwt存入ResponseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:" + userId, loginUser);
        return new ResponseResult(200, "登录成功", map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if (!Objects.isNull(loginUser)){
            String userId = loginUser.getUser().getId().toString();
            String redisKey = "login:"+userId;
            redisCache.deleteObject(redisKey);
        }
        return new ResponseResult(200,"注销成功");
    }

}
